package com.tanhua.dubbo.server.api;


import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.Sound;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@Service(version = "1.0.0")
public class SoundApiImpl implements SoundApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveSound(Sound sound) {
        //判断是否为空
        if(null==sound.getUserId()){
            return null;
        }
        //设置主键id
        sound.setId(ObjectId.get());
        //设置创建时间
        sound.setCreated(System.currentTimeMillis());

        //保存在mongodb中
        mongoTemplate.save(sound);
        return sound.getId().toHexString();
    }

    @Override
    public List<Sound> querySoundList(Long userId) {
        //获取近3天之内的音频259200000
        Query query = new Query();
        List<Sound> soundList = mongoTemplate.find(query, Sound.class);
        //创建一个集合用户保存userId,获取音频用户自己发送的音频
        ArrayList<Long> userIds = new ArrayList<>();
        for (Sound sound : soundList) {
            //获取每个sound的userId
            Long soundUserId = sound.getUserId();
            if((!userIds.contains(sound.getUserId()))&(soundUserId!=userId)){
                userIds.add(sound.getUserId());
            }
        }

        Query query2 = Query.query(Criteria.where("userId").in(userIds).andOperator(Criteria.where("created").gt(System.currentTimeMillis()-259200000)));

        List<Sound> soundList2 = mongoTemplate.find(query2, Sound.class);
        return soundList2;
    }

    @Override
    public Sound queryById(String soundId) {
        return mongoTemplate.findById(new ObjectId(soundId), Sound.class);
    }
}